package com.aaa.test1.servlet;



import com.aaa.test1.dao.AdminDAO;
import com.aaa.test1.dao.impl.AdminDAOImpl;
import com.aaa.test1.result.AjaxResult;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;


@WebServlet("/admin/*")
public class AdminServlet extends HttpServlet {
   private   AdminDAO adminDAO = new AdminDAOImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/json;charset=UTF-8");
        String requestURI = req.getRequestURI();
        String[] split = requestURI.split("/");
        String path = split[split.length - 1];

        if ("login".equals(path)) {
            login(req, resp);
        }else if ("getAdminInfo".equals(path)){
            getAdminInfo(req,resp);
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1 接受账号密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 2 调用dao 验证账号密码是否正确
        Map<String,Object> admin = adminDAO.Login(username,password);
        PrintWriter out = resp.getWriter();
        if (admin == null) {
            AjaxResult ajaxResult = new AjaxResult(50001, "对不起密码错误", null);
            String s = JSON.toJSONString(ajaxResult);
            out.write(s);
        } else {
            req.getSession().setAttribute("admin",admin);
            AjaxResult ajaxResult = new AjaxResult(20001, "登录成功", null);
            String s = JSON.toJSONString(ajaxResult);
            out.write(s);
        }

    }
    protected void getAdminInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object admin = req.getSession().getAttribute("admin");
        PrintWriter out = resp.getWriter();
        AjaxResult result = new AjaxResult(20002, "获取用户信息成功", admin);
        String s = JSON.toJSONString(result);
        out.write(s);
    }
}